import useMappingProps from 't/common/hooks/useMappingProps';
import { computed, nextTick, ref,watch } from "vue";
// import { options } from '../mock';
export const useUtils = (props,emit) => {
  const modelValue =ref()
  const guid = 'id_'+Funcs.Guid().replace(/-/ig,'_')
  let [mappingProps, mappingExpose] = useMappingProps(props,{
    modelValue: modelValue,
  })
  //当前实例
  const refComponent = ref();
  const fieldValue = ref('');
  const filter = ref('');
  const refField = ref();
  const isShow = ref(false);
  const selectTreeHelperContent =  ref()
  const selectTreeHelperInputContent = ref()
  const select_tree_helper_input = ref()
  //回显数据
  const displayingResults = ref()
  //弹出框
  const refTPopupProxy = ref();
  const isClose = ref(false)
  const isOpen = ref(false)
  // 外部传递的 options
  const externalOptions = ref(null)
  // 原始 record 对象，用于直接更新字段值
  const record = ref(null)
  //方法
  const InputFocus = async (e) => {
    e.stopPropagation();
    e.preventDefault()
    if( isClose.value||isOpen.value||mappingProps.readonly||mappingProps.readOnly||mappingProps.isDev) return false
    isShow.value = true
    await nextTick()
    console.log(refTPopupProxy.value)
    refTPopupProxy?.value?.show&&refTPopupProxy?.value?.show()

    return false
  }
  const sizeIsChange = ref('')
  //屏幕尺寸
  const FieldWidth = computed(() => {
    console.log(refField.value)
    const width = refField.value
      ? refField.value.$el
        .querySelector('.q-field__inner')
        .getBoundingClientRect().width
      : 0;
    return width + 'px;version:' + sizeIsChange.value;
  });
  let displayDataSource =''
  let displayMapping =''
  try {
    displayDataSource = mappingProps.valueMapping&&mappingProps.valueMapping.DataSource?.split('.')
    if(displayDataSource){
      displayDataSource = displayDataSource[displayDataSource.length-1]
    }

    displayMapping = mappingProps.displayMapping&&mappingProps.displayMapping.split('.')
    if(displayMapping){
      displayMapping = displayMapping[displayMapping.length-1]
    }
  } catch (error) {

  }
  if(!displayDataSource){
    displayDataSource = mappingProps.valueField
  }
  if(!displayMapping){
    displayMapping = mappingProps.labelField
  }
 const getDisplayingResults= computed(() => {
  if(mappingProps.multiple){
    mappingProps.value&&mappingProps.value.forEach&&mappingProps.value.forEach(item=>{
      if(mappingProps.multiple){
        let Obj = {}
        if(displayDataSource){
          Obj[mappingProps.labelField] = item[displayMapping]
        }
        if(displayMapping){
          Obj[mappingProps.valueField] = item[displayDataSource]
        }
        item = Object.assign(item,Obj)
      }
    })
    modelValue.value=mappingProps.value
    return mappingProps.value&&mappingProps.value.length?mappingProps.value:null
  }else{
    if(mappingProps.responseRelationNode!=2){
      modelValue.value=mappingProps.value

      return mappingProps.text
    }else{

      let res = [];
      let proxyName = "";
      if(typeof mappingProps.customResults == 'string'){
        mappingProps.customResults = JSON.parse(mappingProps.customResults)
      }
      mappingProps.customResults.forEach((p, index) => {
        let item = JSON.parse(JSON.stringify(p));
        let getLabel = new Function(
          "element",
          `with(element){
          return element.${item.Label}
       }`
        );
        let getValue = new Function(
          "element",
          `with(element){
        return element.${item.Value}
     }`
        );
        if(!res.find(jj=>jj[mappingProps.valueField]==getValue({LocalVars:  mappingProps.localvars }))){
          let obj = {};
          obj[mappingProps.labelField] = getLabel({LocalVars:  mappingProps.localvars});
          obj[mappingProps.valueField] = getValue({LocalVars: mappingProps.localvars });
          obj.level =  index +1 ;
           if(obj[mappingProps.labelField]&& obj[mappingProps.valueField]){
            res.push(obj);
          }
          proxyName = proxyName
            ?  obj[mappingProps.labelField]?(proxyName + mappingProps.relationIcon + obj[mappingProps.labelField]):proxyName
            :  obj[mappingProps.labelField];
        }

      });
      modelValue.value=res
      return proxyName
    }
  }
 })

 watch(()=>getDisplayingResults.value,(val)=>{
  displayingResults.value = val
 },{
  deep:true,
  immediate:true
 })
  const _confirm = (e) => {
    // if(e&&!mappingProps.multiple){
    //   displayingResults.value=e.proxyName||e.Name
    // }else if(e){
    //   displayingResults.value=e
    // }
    // mappingProps.confirm(e)
    emit('confirm', e)
    close()
  }
  const close = ()=>{
    isClose.value=true
    refTPopupProxy.value?.hide()
    //清空输入框
    filter.value=''
    setTimeout(() => {
      isClose.value=false
    }, 200);
  }
  const clear=()=>{
    emit('clear','')
    emit('update:value', null);
    emit('update:text', null);
    if(mappingProps.responseRelationNode == 2){
      mappingProps.customResults_result&&mappingProps.customResults_result.dataSource&&mappingProps.customResults_result.dataSource.map(item => {
        let Value = null;
        let clearValue = new Function(
          'element',
          `with(element){
            debugger
        return element.${item.Value}=''
     }`,
        );
        clearValue({LocalVars:  mappingProps.localvars });
        })
    }

    modelValue.value=[]
    mappingProps.value=[]
    displayingResults.value=''
  }
  mappingProps.clearValue = clear
  const breadcrumbNavigation = ref([]);

  //提升变量位置，处理每次都被重置的问题∂
const result_m = ref([]);

const checkList = ref([]);
const dataBackUp = ref([]);
const selectList = ref([]);
const result_m_search = ref([])
const content = ref();

  return {
    guid,
    breadcrumbNavigation,
    result_m,
    selectTreeHelperContent,
    checkList,
    dataBackUp,
    selectList,
    result_m_search,
    content,

    FieldWidth,
    refComponent,
    fieldValue,
    mappingProps,
    ...mappingProps, mappingExpose,
    filter,
    InputFocus,
    refField,
    refTPopupProxy,
    isShow,
    selectTreeHelperContent,
    selectTreeHelperInputContent,
    displayingResults,
    _confirm,
    select_tree_helper_input,
    isOpen,
    isClose,
    clear,
    close,
    clearValue:clear,
    test: () => { alert(1) },
    displayDataSource,
    displayMapping,
    getDisplayingResults,
    sizeIsChange,
    externalOptions,
    record
  }
}
